<template>
  <div class="manage-view">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h2>
            <el-icon><Folder /></el-icon>
            {{ $t('workReports.layout.tabs.manage') }}
          </h2>
          <p>{{ $t('workReports.manage.toolbar.search') }}</p>
        </div>
        <div class="action-section">
          <el-button type="primary" @click="goToGenerate">
            <el-icon><Plus /></el-icon>
            {{ $t('workReports.manage.generateNew') }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 搜索筛选栏 -->
    <el-card class="filter-card" shadow="never">
      <div class="filter-bar">
        <div class="filter-left">
          <el-input
            v-model="searchKeyword"
            :placeholder="$t('workReports.manage.toolbar.searchPlaceholder')"
            style="width: 300px"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-select
            v-model="filters.type"
            :placeholder="$t('workReports.manage.filters.reportType')"
            style="width: 120px"
            clearable
            @change="handleSearch"
          >
            <el-option :label="$t('workReports.generate.reportTypes.daily')" value="DAILY" />
            <el-option :label="$t('workReports.generate.reportTypes.weekly')" value="WEEKLY" />
            <el-option :label="$t('workReports.generate.reportTypes.monthly')" value="MONTHLY" />
          </el-select>

          <el-select
            v-model="filters.status"
            :placeholder="$t('workReports.manage.filters.reportStatus')"
            style="width: 120px"
            clearable
            @change="handleSearch"
          >
            <el-option :label="$t('workReports.manage.statusOptions.draft')" value="DRAFT" />
            <el-option :label="$t('workReports.manage.statusOptions.final')" value="FINAL" />
            <el-option :label="$t('workReports.manage.statusOptions.archived')" value="ARCHIVED" />
          </el-select>

          <el-date-picker
            v-model="dateRange"
            type="daterange"
            :range-separator="$t('workReports.statistics.dateRange.separator')"
            :start-placeholder="$t('workReports.statistics.dateRange.startDate')"
            :end-placeholder="$t('workReports.statistics.dateRange.endDate')"
            style="width: 240px"
            @change="handleDateRangeChange"
          />

          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            {{ $t('workReports.manage.actions.search') }}
          </el-button>

          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            {{ $t('workReports.manage.actions.reset') }}
          </el-button>
        </div>

        <div class="filter-right">
          <el-button @click="fetchReportStats">
            <el-icon><DataAnalysis /></el-icon>
            {{ $t('workReports.manage.actions.statistics') }}
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 批量操作栏 -->
    <el-card v-if="selectedReports.length > 0" class="batch-actions-card" shadow="never">
      <div class="batch-actions">
        <span class="selected-info">
          已选择 <strong>{{ selectedReports.length }}</strong> 项
        </span>
        <div class="batch-buttons">
          <el-button type="danger" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
          <el-button @click="handleBatchExport">
            <el-icon><Download /></el-icon>
            批量导出
          </el-button>
          <el-button @click="clearSelection">
            <el-icon><Close /></el-icon>
            取消选择
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 报告列表 -->
    <el-card class="reports-card">
      <div v-loading="reportsLoading" class="reports-container">
        <!-- 空状态 -->
        <div v-if="!reportsLoading && reports.length === 0" class="empty-state">
          <el-icon size="64" color="#C0C4CC"><Document /></el-icon>
          <h3>暂无报告</h3>
          <p v-if="hasActiveFilters">没有找到符合条件的报告，请调整筛选条件</p>
          <p v-else>还没有生成任何报告，快去生成第一个报告吧</p>
          <el-button type="primary" @click="goToGenerate">
            <el-icon><Plus /></el-icon>
            生成报告
          </el-button>
        </div>

        <!-- 报告表格 -->
        <el-table
          v-else
          :data="reports"
          @selection-change="handleSelectionChange"
          stripe
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" />

          <el-table-column prop="title" :label="$t('workReports.manage.table.title')" min-width="200">
            <template #default="{ row }">
              <div class="title-cell">
                <span class="title-text" @click="handleViewReport(row)">{{ row.title }}</span>
                <el-tag v-if="row.isEdited" size="small" type="warning">{{ $t('workReports.manage.table.edited') }}</el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="type" :label="$t('workReports.manage.table.type')" width="80">
            <template #default="{ row }">
              <el-tag :type="getTypeTagType(row.type)" size="small">
                {{ getTypeDisplayName(row.type) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column :label="$t('workReports.manage.table.period')" width="180">
            <template #default="{ row }">
              <div class="date-range">
                <span>{{ formatDate(row.periodStart) }}</span>
                <span v-if="row.periodStart !== row.periodEnd"> {{ $t('workReports.statistics.dateRange.separator') }} {{ formatDate(row.periodEnd) }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="status" :label="$t('workReports.manage.table.status')" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)" size="small">
                {{ getStatusDisplayName(row.status) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="version" :label="$t('workReports.manage.table.version')" width="80" />

          <el-table-column prop="createdAt" :label="$t('workReports.manage.table.createTime')" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.createdAt) }}
            </template>
          </el-table-column>

          <el-table-column :label="$t('workReports.manage.table.actions')" width="200" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button link type="primary" @click="handleViewReport(row)">
                  <el-icon><View /></el-icon>
                  {{ $t('workReports.manage.actions.view') }}
                </el-button>
                <el-button link type="primary" @click="handleEditReport(row)">
                  <el-icon><Edit /></el-icon>
                  {{ $t('workReports.manage.actions.edit') }}
                </el-button>
                <el-dropdown @command="(command) => handleDropdownCommand(command, row)">
                  <el-button link type="primary">
                    {{ $t('workReports.manage.actions.more') }}<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="export">
                        <el-icon><Download /></el-icon>
                        {{ $t('workReports.manage.actions.export') }}
                      </el-dropdown-item>
                      <el-dropdown-item command="delete" divided>
                        <el-icon><Delete /></el-icon>
                        {{ $t('workReports.manage.actions.delete') }}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div v-if="reports.length > 0" class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="totalReports"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Folder, Document, Plus, Search, Refresh, DataAnalysis,
  Delete, Download, Close, View, Edit, ArrowDown
} from '@element-plus/icons-vue'
import { useWorkReportStore } from '@/stores/workReportStore'
import type { GeneratedReport, ReportFilters } from '@/types/workReport'

const { t } = useI18n()
const router = useRouter()
const workReportStore = useWorkReportStore()

// ==================== 响应式数据 ====================

// 搜索和筛选
const searchKeyword = ref('')
const dateRange = ref<[Date, Date] | null>(null)
const filters = ref<ReportFilters>({})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)

// 选择
const selectedReports = ref<GeneratedReport[]>([])

// ==================== 计算属性 ====================

const reports = computed(() => workReportStore.reports)
const reportsLoading = computed(() => workReportStore.reportsLoading)
const reportPagination = computed(() => workReportStore.reportPagination)

const totalReports = computed(() => reportPagination.value.total)

const hasActiveFilters = computed(() => {
  return !!(
    searchKeyword.value ||
    filters.value.type ||
    filters.value.status ||
    filters.value.startDate ||
    filters.value.endDate
  )
})

// ==================== 国际化函数 ====================

const getTypeDisplayName = (type: string) => {
  const typeMap: Record<string, string> = {
    'DAILY': t('workReports.generate.reportTypes.daily'),
    'WEEKLY': t('workReports.generate.reportTypes.weekly'),
    'MONTHLY': t('workReports.generate.reportTypes.monthly'),
    // 兼容小写
    'daily': t('workReports.generate.reportTypes.daily'),
    'weekly': t('workReports.generate.reportTypes.weekly'),
    'monthly': t('workReports.generate.reportTypes.monthly')
  }
  return typeMap[type] || type
}

const getStatusDisplayName = (status: string) => {
  const statusMap: Record<string, string> = {
    'DRAFT': t('workReports.manage.statusOptions.draft'),
    'FINAL': t('workReports.manage.statusOptions.final'),
    'ARCHIVED': t('workReports.manage.statusOptions.archived'),
    // 兼容小写
    'draft': t('workReports.manage.statusOptions.draft'),
    'final': t('workReports.manage.statusOptions.final'),
    'archived': t('workReports.manage.statusOptions.archived')
  }
  return statusMap[status] || status
}

// ==================== 方法 ====================

/**
 * 初始化页面
 */
const initPage = async () => {
  await fetchReports()
}

/**
 * 获取报告列表
 */
const fetchReports = async () => {
  const queryRequest = {
    page: currentPage.value - 1, // 后端从0开始
    size: pageSize.value,
    keyword: searchKeyword.value || undefined,
    type: filters.value.type,
    status: filters.value.status,
    startDate: filters.value.startDate,
    endDate: filters.value.endDate,
    sortBy: 'createdAt',
    sortDirection: 'DESC' as const
  }

  await workReportStore.fetchReports(queryRequest)
}

/**
 * 搜索处理
 */
const handleSearch = async () => {
  currentPage.value = 1 // 重置到第一页
  await fetchReports()
}

/**
 * 重置筛选条件
 */
const handleReset = async () => {
  searchKeyword.value = ''
  dateRange.value = null
  filters.value = {}
  currentPage.value = 1
  await fetchReports()
}

/**
 * 日期范围变化处理
 */
const handleDateRangeChange = (dates: [Date, Date] | null) => {
  if (dates) {
    filters.value.startDate = formatDateForApi(dates[0])
    filters.value.endDate = formatDateForApi(dates[1])
  } else {
    filters.value.startDate = undefined
    filters.value.endDate = undefined
  }
  handleSearch()
}

/**
 * 分页大小变化
 */
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchReports()
}

/**
 * 页码变化
 */
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchReports()
}

/**
 * 选择变化处理
 */
const handleSelectionChange = (selection: GeneratedReport[]) => {
  selectedReports.value = selection
}

/**
 * 清除选择
 */
const clearSelection = () => {
  selectedReports.value = []
}

/**
 * 查看报告
 */
const handleViewReport = (report: GeneratedReport) => {
  router.push({
    name: 'ReportDetail',
    params: { id: report.id },
    query: { mode: 'view' }
  })
}

/**
 * 编辑报告
 */
const handleEditReport = (report: GeneratedReport) => {
  router.push({
    name: 'ReportDetail',
    params: { id: report.id },
    query: { mode: 'edit' }
  })
}

/**
 * 下拉菜单命令处理
 */
const handleDropdownCommand = (command: string, report: GeneratedReport) => {
  switch (command) {
    case 'export':
      handleExportReport(report)
      break
    case 'delete':
      handleDeleteReport(report)
      break
  }
}

/**
 * 导出报告
 */
const handleExportReport = async (report: GeneratedReport) => {
  try {
    await workReportStore.exportReport(report.id, 'PDF')
  } catch (error) {
    console.error('导出报告失败:', error)
  }
}

/**
 * 删除报告
 */
const handleDeleteReport = async (report: GeneratedReport) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除报告"${report.title}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await workReportStore.deleteReport(report.id)
    await fetchReports() // 刷新列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除报告失败:', error)
    }
  }
}

/**
 * 批量删除
 */
const handleBatchDelete = async () => {
  if (selectedReports.value.length === 0) {
    ElMessage.warning('请先选择要删除的报告')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedReports.value.length} 个报告吗？此操作不可恢复。`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const reportIds = selectedReports.value.map(r => r.id)
    await workReportStore.batchDeleteReports(reportIds)

    clearSelection()
    await fetchReports() // 刷新列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
    }
  }
}

/**
 * 批量导出
 */
const handleBatchExport = async () => {
  if (selectedReports.value.length === 0) {
    ElMessage.warning('请先选择要导出的报告')
    return
  }

  ElMessage.info('批量导出功能开发中，敬请期待')
}

/**
 * 获取统计信息
 */
const fetchReportStats = async () => {
  try {
    await workReportStore.fetchReportStats()
    ElMessage.success('统计信息已更新')
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

/**
 * 跳转到生成报告页面
 */
const goToGenerate = () => {
  router.push({ name: 'ReportGenerate' })
}

// ==================== 工具方法 ====================

/**
 * 格式化日期用于API
 */
const formatDateForApi = (date: Date): string => {
  return date.toISOString().split('T')[0]
}

/**
 * 格式化日期显示
 */
const formatDate = (dateStr: string): string => {
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN')
}

/**
 * 格式化日期时间显示
 */
const formatDateTime = (dateTimeStr: string): string => {
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

/**
 * 获取类型标签类型
 */
const getTypeTagType = (type: string): string => {
  const typeMap: Record<string, string> = {
    'DAILY': 'primary',
    'WEEKLY': 'success',
    'MONTHLY': 'warning'
  }
  return typeMap[type] || 'info'
}

/**
 * 获取状态标签类型
 */
const getStatusTagType = (status: string): string => {
  const statusMap: Record<string, string> = {
    'DRAFT': 'info',
    'FINAL': 'success',
    'ARCHIVED': 'warning'
  }
  return statusMap[status] || 'info'
}

// ==================== 生命周期 ====================

onMounted(() => {
  initPage()
})

// 监听分页变化
watch([currentPage, pageSize], () => {
  fetchReports()
})

</script>

<style scoped lang="scss">
.manage-view {
  background-color: var(--el-bg-color-page);
}

// 页面头部
.page-header {
  margin-bottom: 20px;

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .title-section {
      h2 {
        margin: 0 0 8px 0;
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 24px;
        color: var(--el-text-color-primary);
        font-weight: 600;
      }

      p {
        margin: 0;
        color: var(--el-text-color-regular);
        font-size: 14px;
      }
    }

    .action-section {
      display: flex;
      gap: 12px;
    }
  }
}

// 筛选卡片
.filter-card {
  margin-bottom: 16px;

  .filter-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;

    .filter-left {
      display: flex;
      align-items: center;
      gap: 12px;
      flex-wrap: wrap;
    }

    .filter-right {
      display: flex;
      gap: 8px;
    }
  }
}

// 批量操作卡片
.batch-actions-card {
  margin-bottom: 16px;
  border: 1px solid var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);

  .batch-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .selected-info {
      color: var(--el-color-primary);
      font-weight: 500;

      strong {
        font-weight: 600;
      }
    }

    .batch-buttons {
      display: flex;
      gap: 8px;
    }
  }
}

// 报告卡片
.reports-card {
  .reports-container {
    min-height: 400px;
  }
}

// 空状态
.empty-state {
  text-align: center;
  padding: 80px 20px;

  h3 {
    margin: 16px 0 8px 0;
    color: var(--el-text-color-primary);
    font-size: 18px;
  }

  p {
    margin: 0 0 24px 0;
    color: var(--el-text-color-regular);
    font-size: 14px;
  }
}

// 表格样式
.title-cell {
  display: flex;
  align-items: center;
  gap: 8px;

  .title-text {
    cursor: pointer;
    color: var(--el-color-primary);
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }
}

.date-range {
  font-size: 13px;
  color: var(--el-text-color-regular);
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

// 分页容器
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid var(--el-border-color-lighter);
}

// 响应式设计
@media (max-width: 768px) {
  .manage-view {
    padding: 12px;
  }

  .page-header .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .filter-bar {
    flex-direction: column;
    align-items: stretch !important;
    gap: 12px !important;

    .filter-left {
      flex-direction: column;
      align-items: stretch;
      gap: 8px;
    }

    .filter-right {
      justify-content: center;
    }
  }

  .batch-actions {
    flex-direction: column;
    gap: 12px;
    align-items: stretch !important;

    .batch-buttons {
      justify-content: center;
    }
  }
}

// 暗色主题适配
@media (prefers-color-scheme: dark) {
  .batch-actions-card {
    background-color: var(--el-color-primary-dark-2);
  }
}
</style>
